//
//  XYCRouter.m
//  WLRRoute_Example
//
//  Created by xyc on 2018/2/6.
//  Copyright © 2018年 Neo. All rights reserved.
//

#import "XYCRouter.h"
#import "XYCRouteRequest.h"
#import "XYCRouteMatcher.h"
#import "NSError+XYCRouteError.h"
#import <UIKit/UIKit.h>

@interface XYCRouter()

@property(nonatomic,strong)NSMutableDictionary * routeHandles;  //使用handle方式的话，所有handle都放这里
@property(nonatomic,strong)NSMutableDictionary * routeMatchers; //对应每一个handle／block都有一个matcher与之对应

@end

@implementation XYCRouter

+ ( instancetype ) sharedInstance {
    static id sharedInstance = nil ;
    static dispatch_once_t onceToken ;
    dispatch_once ( &onceToken , ^{
        sharedInstance = [[self alloc] init];
    } );
    return sharedInstance ;
}

-(instancetype)init{
    if (self = [super init]) {
        _routeHandles = [NSMutableDictionary dictionary];
        _routeMatchers = [NSMutableDictionary dictionary];
    }
    return self;
}
// 限制方法，类只能初始化一次 alloc 的时候调用
+ ( id ) allocWithZone:( struct _NSZone *)zone{
    
    static id sharedInstance = nil ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
    });
    return sharedInstance;
}

//// 拷贝方法
//- ( id )copyWithZone:( NSZone *)zone{
//    
//    NSLog(@"copyWithZone");
//    return [XYCRouter sharedInstance];
//}

-(void)registerHandler:(XYCRouteHandler*)handler forRoute:(NSString*)route{
    
    if (route && route.length) {
        
        self.routeHandles[route] = handler;//保存注册的handler
        [self.routeMatchers setObject:[XYCRouteMatcher matcherWithRouteExpression:route] forKey:route];
    }
}

-(BOOL)handleURL:(NSURL *)URL primitiveParameters:(NSDictionary *)primitiveParameters completionBlock:(void(^)(BOOL handled, NSError *error))completionBlock{
    if (!URL) {
        
        return NO;
    }
    
    NSError * error = nil;
    XYCRouteRequest * request = nil;
    BOOL isHandled = NO;
    
    //遍历matcher，创建适合route的request
    for (NSString * route in self.routeMatchers.allKeys) {
        
        XYCRouteMatcher * matcher = [self.routeMatchers objectForKey:route];
        request = [matcher createRequestWithURL:URL primitiveParameters:primitiveParameters];
        if (request) {
            
            isHandled = [self handleRouteExpression:route withRequest:request error:&error];
            break;
        }
    }
    if (!request) {
        
        //没有找到对应的路由
        error = [NSError XYCRouteNotFoundError];
    }
    //路由走完的回调
    [self completeRouteWithSuccess:isHandled error:error completionHandler:completionBlock];
    return isHandled;
}

-(BOOL)handleRouteExpression:(NSString *)routeExpression withRequest:(XYCRouteRequest *)request error:(NSError *__autoreleasing *)error {
    
    id handler = self.routeHandles[routeExpression];        // 取出handle
    XYCRouteHandler * rHandler = (XYCRouteHandler *)handler;
    return [rHandler handleRequest:request error:error];    // 开始处理跳转
}

- (void)completeRouteWithSuccess:(BOOL)handled error:(NSError *)error completionHandler:(void(^)(BOOL handled, NSError *error))completionHandler {
    if (completionHandler) {
        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(handled, error);
        });
    }
}

@end
